package handlers

import (
	"fmt"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"

	"script-management/internal/services"
)

// Handler 处理HTTP请求
type Handler struct {
	scriptService *services.ScriptService
	venvService   *services.VenvService
	systemService *services.SystemService
}

// NewHandler 创建一个新的处理器实例
func NewHandler(scriptService *services.ScriptService, venvService *services.VenvService, systemService *services.SystemService) *Handler {
	return &Handler{
		scriptService: scriptService,
		venvService:   venvService,
		systemService: systemService,
	}
}

// Home 显示首页
func (h *Handler) Home(c *gin.Context) {
	scripts, err := h.scriptService.ListScripts()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": fmt.Sprintf("获取脚本列表失败: %v", err),
		})
		return
	}

	// 获取最近运行的脚本（这里暂时使用所有脚本代替）
	c.HTML(http.StatusOK, "index.html", gin.H{
		"scripts": scripts,
	})
}

// ManageScripts 显示脚本管理页面
func (h *Handler) ManageScripts(c *gin.Context) {
	scripts, err := h.scriptService.ListScripts()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": fmt.Sprintf("获取脚本列表失败: %v", err),
		})
		return
	}

	availableVenvs, err := h.venvService.ListVenvs()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": fmt.Sprintf("获取虚拟环境列表失败: %v", err),
		})
		return
	}

	c.HTML(http.StatusOK, "scripts.html", gin.H{
		"scripts":        scripts,
		"availableVenvs": availableVenvs,
	})
}

// AddScript 添加新脚本
func (h *Handler) AddScript(c *gin.Context) {
	// 获取表单数据
	name := c.PostForm("name")
	if name == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "脚本名称不能为空"})
		return
	}

	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("获取上传文件失败: %v", err)})
		return
	}

	// 读取文件内容
	f, err := file.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("读取文件失败: %v", err)})
		return
	}
	defer f.Close()

	// 创建文件内容映射
	files := make(map[string][]byte)
	content := make([]byte, file.Size)
	if _, err := f.Read(content); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("读取文件内容失败: %v", err)})
		return
	}
	files["main.py"] = content

	// 添加脚本
	if err := h.scriptService.AddScript(name, files); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("添加脚本失败: %v", err)})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "脚本添加成功"})
}

// GetScript 获取脚本信息
func (h *Handler) GetScript(c *gin.Context) {
	name := c.Param("id")
	script, err := h.scriptService.GetScript(name)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, script)
}

// DeleteScript 删除脚本
func (h *Handler) DeleteScript(c *gin.Context) {
	name := c.Param("id")
	if err := h.scriptService.DeleteScript(name); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "脚本删除成功"})
}

// RunScript 运行脚本
func (h *Handler) RunScript(c *gin.Context) {
	name := c.Param("id")
	venvName := c.PostForm("venv")

	var venvPath string
	if venvName != "" {
		venvInfo, err := h.venvService.GetVenvInfo(venvName)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("获取虚拟环境信息失败: %v", err)})
			return
		}
		venvPath = venvInfo.Path
	}

	if err := h.scriptService.RunScript(name, venvPath); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "脚本启动成功"})
}

// StopScript 停止脚本
func (h *Handler) StopScript(c *gin.Context) {
	name := c.Param("id")
	if err := h.scriptService.StopScript(name); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "脚本停止成功"})
}

// GetScriptStatus 获取脚本状态
func (h *Handler) GetScriptStatus(c *gin.Context) {
	name := c.Param("id")
	status := h.scriptService.GetScriptStatus(name)
	c.JSON(http.StatusOK, gin.H{"status": status})
}

// ManageFiles 显示文件管理页面
func (h *Handler) ManageFiles(c *gin.Context) {
	name := c.Param("id")
	script, err := h.scriptService.GetScript(name)
	if err != nil {
		c.HTML(http.StatusNotFound, "error.html", gin.H{
			"error": err.Error(),
		})
		return
	}

	c.HTML(http.StatusOK, "manage_files.html", gin.H{
		"script": script,
	})
}

// SaveFile 保存文件内容
func (h *Handler) SaveFile(c *gin.Context) {
	name := c.Param("id")
	filename := c.Param("filename")
	content := []byte(c.PostForm("content"))

	if err := h.scriptService.WriteFile(name, filename, content); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "文件保存成功"})
}

// DownloadScript 下载脚本
func (h *Handler) DownloadScript(c *gin.Context) {
	name := c.Param("id")
	zipPath, err := h.scriptService.CreateZip(name)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer os.Remove(zipPath)

	c.FileAttachment(zipPath, name+".zip")
}

// ManageVenvs 显示虚拟环境管理页面
func (h *Handler) ManageVenvs(c *gin.Context) {
	venvs, err := h.venvService.ListVenvs()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "error.html", gin.H{
			"error": fmt.Sprintf("获取虚拟环境列表失败: %v", err),
		})
		return
	}

	c.HTML(http.StatusOK, "venvs.html", gin.H{
		"venvs": venvs,
	})
}

// CreateVenv 创建虚拟环境
func (h *Handler) CreateVenv(c *gin.Context) {
	name := c.PostForm("name")
	version := c.PostForm("version")
	if name == "" || version == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "名称和Python版本不能为空"})
		return
	}

	if err := h.venvService.CreateVenv(name, version); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "虚拟环境创建成功"})
}

// DeleteVenv 删除虚拟环境
func (h *Handler) DeleteVenv(c *gin.Context) {
	name := c.Param("id")
	if err := h.venvService.DeleteVenv(name); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "虚拟环境删除成功"})
}

// InstallPackage 安装包
func (h *Handler) InstallPackage(c *gin.Context) {
	venvName := c.Param("id")
	packageName := c.PostForm("package")
	if packageName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "包名不能为空"})
		return
	}

	if err := h.venvService.InstallPackage(venvName, packageName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "包安装成功"})
}

// UninstallPackage 卸载包
func (h *Handler) UninstallPackage(c *gin.Context) {
	venvName := c.Param("id")
	packageName := c.Param("package")

	if err := h.venvService.UninstallPackage(venvName, packageName); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "包卸载成功"})
}

// GetSystemResources 获取系统资源信息
func (h *Handler) GetSystemResources(c *gin.Context) {
	resources, err := h.systemService.GetSystemResources()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, resources)
}
